package cn.itcast.demo.task;

import cn.itcast.demo.lock.RedisLock;
import cn.itcast.demo.lock.RedisLockFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;

/**
 * @author 虎哥
 */
@Slf4j
//@Component
public class LockTask {

    // 获取锁对象
    private RedisLock lock;

    public LockTask(RedisLockFactory factory) {
        lock = factory.getReenTrantRedisLock("lock");
    }

    @Scheduled(cron = "0/10 * * * * ?")
    public void job(){
        log.warn("尝试获取锁");
        // 尝试获取锁
        boolean isLock = lock.tryLock(200);
        // 判断是否成功
        if(!isLock){
            // 获取锁失败，任务终止
            log.error("获取锁失败，任务结束！");
            return;
        }
        try {
            // 获取锁成功，开始执行任务
            log.info("获取锁成功，开始执行业务");
            clearOrder();
        }finally {
            log.warn("任务执行结束，释放锁");
            // 释放锁
            lock.unlock();
        }
    }

    private void clearOrder() {
        try {
            // 默认任务延迟
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
